package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.bean.sysuser.SysUserRoleDO;
import com.example.demo.exception.OtherException;
import com.example.demo.mapper.sysuser.SysUserRoleMapper;
import com.example.demo.service.ISysUserRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRoleDO> implements ISysUserRoleService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public int deleteUserRoleByUserId(Long userId) {
        QueryWrapper<SysUserRoleDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return sysUserRoleMapper.delete(queryWrapper);
    }

    @Override
    public int addSysUserRole(SysUserRoleDO sysUserRoleDO) {
        deleteUserRoleByUserId(sysUserRoleDO.getUserId());
        return sysUserRoleMapper.insert(sysUserRoleDO);
    }

    @Override
    public SysUserRoleDO getSysUserRole(Long userId) {
        validSysUserRoleExist(userId);
        QueryWrapper<SysUserRoleDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return sysUserRoleMapper.selectOne(queryWrapper);
    }

    private void validSysUserRoleExist(Long userId){
        QueryWrapper<SysUserRoleDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        SysUserRoleDO exist = sysUserRoleMapper.selectOne(queryWrapper);
        if(exist == null){
            throw new OtherException("用户尚未分配权限");
        }
    }
}
